/* ========================================================================
 * PROJECT: FTIR Blob Tracker
 * ========================================================================
 * This work is based on the original FTIR Blob Tracker developed by
 *   Woonhyuk Baek
 *   Woontack Woo
 *   U-VR Lab, GIST of Gwangju in Korea.
 *   
 *   http://uvr.gist.ac.kr/
 *
 * Copyright of the derived and new portions of this work
 *     (C) 2009 GIST U-VR Lab.
 *
 * This framework is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this framework; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * For further information please contact 
 *   Woonhyuk Baek
 *   <windage@live.com>
 *   GIST U-VR Lab.
 *   Department of Information and Communication
 *   Gwangju Institute of Science and Technology
 *   1, Oryong-dong, Buk-gu, Gwangju
 *   South Korea
 * ========================================================================
 ** @author   Woonhyuk Baek
 * ======================================================================== */

#include "BlobDetector.h"

int BlobDetector::Do()
{
	this->blobList.clear();
	if(this->inputImage == NULL)
		return -1;

	CvMemStorage* blobStorage = NULL;
	CvSeq* blobContours = 0;

	blobStorage = cvCreateMemStorage(0);
	int count = cvFindContours(this->inputImage, blobStorage, &blobContours, sizeof(CvContour), CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));
	if(count > 0)
		blobContours = cvApproxPoly( blobContours, sizeof(CvContour), blobStorage, CV_POLY_APPROX_DP, 3, 1 );

	while(blobContours != NULL)
	{
		float area = (float)fabs(cvContourArea(blobContours, CV_WHOLE_SEQ));
		if(this->minBlobArea < area && area < this->maxBlobArea)
		{
			CvRect outerBox = cvContourBoundingRect(blobContours);
			CvBox2D32f innerBox = cvMinAreaRect2(blobContours);

			BlobPoint center;
			center.x = (double)(outerBox.x + outerBox.width/2);
			center.y = (double)(outerBox.y + outerBox.height/2);

			Blob tempBlob;
			tempBlob.pt = center;
			tempBlob.area = area;
			tempBlob.boundingRect = outerBox;
			tempBlob.angle = innerBox.angle;
			tempBlob.length = sqrt(area);

			this->blobList.push_back(tempBlob);
		}
		blobContours = blobContours->h_next;
	}

	cvReleaseMemStorage(&blobStorage);
	return 0;
}